#!/usr/bin/env python
#
# Copyright (C) 2011 Clement Lorteau <clem@lorteau.fr>	
#		
# This file is part of QuickScreenShots.		
# 	
# This program is free software; you can redistribute it and/or modify	
# it under the terms of the GNU General Public License as published by		
# the Free Software Foundation; version 3.	
# 	
# This program is distributed in the hope that it will be useful,		
# but WITHOUT ANY WARRANTY; without even the implied warranty of		
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the		
# GNU General Public License for more details.		
# 		
# You should have received a copy of the GNU General Public License		
# along with this program; if not, write to the Free Software		
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

import platform

if platform.system() == 'Windows':
	import sys
	import os
	from distutils.core import setup
	import py2exe
	import shutil
	import fnmatch
	
	use_upx = 'noupx' not in sys.argv
	if not use_upx:
		sys.argv.remove('noupx')
	
	sys.argv.append('py2exe')
	
	# manifest is to get windows visual styles working
	# pythonhaven.wordpress.com/2009/10/07/how-to-get-xp-styles-on-wxpython-apps-made-with-py2exe
	manifest = """
	<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
	<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
	  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
		<security>
		  <requestedPrivileges>
			<requestedExecutionLevel level='asInvoker' uiAccess='false' />
		  </requestedPrivileges>
		</security>
	  </trustInfo>
	  <dependency>
		<dependentAssembly>
		  <assemblyIdentity
		 type='win32'
		 name='Microsoft.VC90.CRT'
		 version='9.0.21022.8'
		 processorArchitecture='*'
		 publicKeyToken='1fc8b3b9a1e18e3b' />
		</dependentAssembly>
	  </dependency>
	  <dependency>
		<dependentAssembly>
		  <assemblyIdentity
			 type="win32"
			 name="Microsoft.Windows.Common-Controls"
			 version="6.0.0.0"
			 processorArchitecture="*"
			 publicKeyToken="6595b64144ccf1df"
			 language="*" />
		</dependentAssembly>
	  </dependency>
	</assembly>
	"""
	mfcdir = 'C:\\Python27\\Lib\\site-packages\\pythonwin\\'
	mfcfiles = [mfcdir+"mfc90.dll",
				mfcdir+"mfc90u.dll",
				mfcdir+"mfcm90.dll",
				mfcdir+"mfcm90u.dll",
				mfcdir+"Microsoft.VC90.MFC.manifest"]
	resources = []
	for f in os.listdir('resources'):
		resources.append('resources/'+f)
		
	if not os.path.exists('../deliverable'):
			os.makedirs('../deliverable')
	
	setup(
		options = {'py2exe': {
							'optimize': 2,
							# 'bundle_files': 1,
							'compressed': True,
							'dist_dir': '../deliverable',
							'dll_excludes': 'MSVCP90.dll'
					 }},
		windows = [{
				 'script': 'qss.py',
				 'icon_resources': [(1, 'resources/snapshot.ico')],
				 'other_resources' : [(24, 1, manifest)]
				}],
		zipfile = "lib/sharedlib",
		data_files = [("Microsoft.VC90.MFC", mfcfiles),
					  ("resources", resources)],
		)
	
	# os.unlink('../deliverable/w9xpopen.exe')
	shutil.rmtree('build')
	rename_exes = {'../deliverable/qss.exe': '../deliverable/quickscreenshots.exe'}
	
	for old, new in rename_exes.iteritems():
	
		if os.path.exists(new):
			os.unlink(new)
	
		print "Renaming %s to %s" % (old, new)
		os.rename(old, new)
	
	if use_upx:
		upx = 'upx.exe --best'
		target = '..\deliverable'
		print 'Compressing better'
		for root, dirs, files in os.walk(target):
			for file in files:
				if fnmatch.fnmatch(file, '*.dll') or fnmatch.fnmatch(file, '*.exe') or fnmatch.fnmatch(file, '*.pyd'):
					os.system("%s \"%s\\%s\"" % (upx, root, file))
					
elif platform.system() == 'Darwin':
	import sys
	import os
	import shutil
	from setuptools import setup
	from __init__ import __version__
	
	sys.argv.append('py2app')
	
	resources = ['resources']
	for f in os.listdir('.'):
		if f[-3:] == '.py':
			resources.append(f)

	APP = ['qss.py']
	DATA_FILES = resources
	OPTIONS = {'argv_emulation': True,
			   'iconfile': 'resources/snapshot.icns',
			   'optimize': 2,
			   'plist':{'CFBundleDisplayName': 'QuickScreenShots',
				 		   'CFBundleExecutable': 'QuickScreenShots',
				 		   'CFBundleName': 'QuickScreenShots',
				 		   'CFBundleShortVersionString': __version__,
				 		   'CFBundleVersion': __version__,
				 		   'NSHumanReadableCopyright': '(c) Clement Lorteau 2011'}
			  }
	
	setup(
		app=APP,
		data_files=DATA_FILES,
		options={'py2app': OPTIONS},
		setup_requires=['py2app'],
	)
	
	if not os.path.exists('../deliverable'):
			os.makedirs('../deliverable')
	if os.path.exists('../deliverable/QuickScreenShots.app'):
		os.unlink('../deliverable/QuickScreenShots.app')
	os.rename('dist/QuickScreenShots.app', '../deliverable/QuickScreenShots.app')
	shutil.rmtree('dist')
	shutil.rmtree('build')